<?php
namespace App\Controllers\Admin\System;

use App\Components\Admin\Menu;
use App\Components\Admin\Node;
use App\Components\Admin\ResponseHelper;
use App\Components\Admin\Router;
use App\Components\Twig\Twig;
use App\Models\System\SystemMenu;
use Exception;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * 系统菜单
 */
class MenuController
{
    /**
     * 菜单列表
     * @auth
     * @menu
     */
    public function index(Request $request, Response $response)
    {
        $params = $request->getQueryParams();
        $params = array_filter($params);
        !isset($params['status']) && $params['status'] = 1;
        if (!in_array($params['status'], [1, 2])) {
            $params['status'] = 1;
        }

        $listRs = SystemMenu::select(
            'id', 'pid', 'title', 'icon', 'color', 'node', 'parameter',
            'orders', 'status'
        )->orderBy('orders', 'desc')
            ->orderBy('id', 'asc')->get()->toArray();
        $tree = [];
        nodeTree($listRs, $tree);
        $tree = nodeTreeValue($tree);

        $tree = Menu::treeFilter($tree, $params['status']);
        $tree = SystemMenu::menuNodeToNull($tree);

        $view = Twig::fromRequest($request);
        $response->getBody()->write($view->fetch('admin/system/menu/index.html', [
            'title' => '系统菜单列表',
            'list' => $tree,
            'status' => $params['status'],
        ]));
        return $response;
    }

    /**
     * 编辑菜单
     * @auth
     */
    public function edit(Request $request, Response $response)
    {
        $node = [];
        $nodeRs = Node::availableNode();
        foreach ($nodeRs as $v1) {
            foreach ($v1['children'] as $v2) {
                if (!isset($v2['menu']) || $v2['menu'] !== true) {
                    continue;
                }
                $node[] = [
                    'url' => Router::ControllerToUriPath($v1['node'], $v2['node']),
                    'title' => $v2['name'],
                ];
            }
        }
        unset($nodeRs);

        $menuRs = SystemMenu::select('id', 'pid', 'title')
            ->where('status', 1)
            ->orderBy('orders', 'desc')
            ->get()->toArray();

        if ($request->getMethod() == 'POST') {
            $params = $request->getParsedBody();
            $params = array_filter($params);
            !isset($params['pid']) && $params['pid'] = 0;
            if ($params['pid'] < 0) {
                return ResponseHelper::error($response, '上级菜单选择错误');
            }
            if (!isset($params['title'])) {
                return ResponseHelper::error($response, '请输入菜单名称');
            }
            if (mb_strlen($params['title']) > 30) {
                return ResponseHelper::error($response, '菜单名称不能超过30个文字');
            }
            !isset($params['node']) && $params['node'] = '#';
            if ($params['node'] != '#') {
                $tempNode = array_column($node, 'url');
                if (!in_array($params['node'], $tempNode)) {
                    return ResponseHelper::error($response, '菜单链接有错误');
                }
                unset($tempNode);
            }
            if (isset($params['parameter']) && strpos($params['parameter'], '?') === 0) {
                $params['parameter'] = substr($params['parameter'], 1);
            }
            !isset($params['icon']) && $params['icon'] = 'far fa-circle';
            if (isset($params['id']) && $params['id'] > 0) {
                $menu = SystemMenu::find($params['id']);
                if (!isset($menu->id)) {
                    return ResponseHelper::error($response, '参数ID错误');
                }
                if ($params['pid'] != $menu->pid) {
                    $menu->pid = $params['pid'];
                }
                if ($params['title'] != $menu->title) {
                    $menu->title = $params['title'];
                }
                if ($params['icon'] != $menu->icon) {
                    $menu->icon = $params['icon'];
                }
                !isset($params['color']) && $params['color'] = '';
                if ($params['color'] != $menu->color) {
                    $menu->color = $params['color'];
                }
                if ($params['node'] != $menu->node) {
                    $menu->node = $params['node'];
                }
                !isset($params['parameter']) && $params['parameter'] = '';
                if ($params['parameter'] != $menu->parameter) {
                    $menu->parameter = $params['parameter'];
                }
                $menu->save();
            } else {
                $menu = new SystemMenu;
                $menu->pid = $params['pid'];
                $menu->title = $params['title'];
                $menu->icon = $params['icon'];
                $menu->color = $params['color'] ?? '';
                $menu->node = $params['node'];
                $menu->parameter = $params['parameter'] ?? '';
                $menu->orders = 0;
                $menu->status = 1;
                $menu->save();
                if (!isset($menu->id) || $menu->id <= 0) {
                    return ResponseHelper::error($response, '菜单添加错误');
                }
            }

            SystemMenu::clearAllMenuCache();

            return ResponseHelper::success($response);
        }

        $params = $request->getQueryParams();
        $params = array_filter($params);
        if (isset($params['id']) && $params['id'] > 0) {
            $infoRs = SystemMenu::where('id', $params['id'])->first();
            if (!isset($infoRs->id)) {
                throw new Exception('菜单未找到');
            }
            $infoRs = $infoRs->toArray();

            $title = '编辑系统菜单';
        } else {
            $title = '新增系统菜单';
            if (isset($params['pid']) && $params['pid'] >= 0) {
                $infoRs['pid'] = $params['pid'];
            }
        }

        $menu = $menuRs;
        $tree = [];
        nodeTree($menu, $tree);
        $tree = nodeTreeValue($tree);

        $view = Twig::fromRequest($request);
        $response->getBody()->write($view->fetch('admin/system/menu/edit.html', [
            'title' => $title,
            'node' => $node,
            'menu' => $tree,
            'info' => $infoRs ?? [],
        ]));
        return $response;
    }

    /**
     * 菜单图标
     * @auth
     */
    public function icon(Request $request, Response $response)
    {
        // 将其所有字体，根据官方分类，使用TAB分割
        // $cssContent = ROOT_PATH . 'public/adminlte/plugins/fontawesome-free/css/all.min.css';
        // $cssContent = file_get_contents($cssContent);
        // $cssContent = explode('}', $cssContent);
        // foreach ($cssContent as $k => $v) {
        //     if (strpos($v, ':before{content:') === false) {
        //         unset($cssContent[$k]);
        //         continue;
        //     }
        //     $v = substr($v, 0, strpos($v, ':before{content:'));
        //     $cssContent[$k] = substr($v, 1);
        // }
        // $cssContent = array_values($cssContent);

        $view = Twig::fromRequest($request);
        $response->getBody()->write($view->fetch('admin/system/menu/icon.html', [
            'title' => '菜单图标',
            // 'list' => $cssContent,
        ]));
        return $response;
    }

    /**
     * 菜单状态
     * @auth
     */
    public function state(Request $request, Response $response)
    {
        if ($request->getMethod() == 'POST') {
            $params = $request->getParsedBody();
            if (!isset($params['id']) || $params['id'] <= 0) {
                return ResponseHelper::error($response, '参数ID错误');
            }
            if (isset($params['action']) && $params['action'] == 'orders') {
                if (!isset($params['orders']) || $params['orders'] < 0 ||
                    $params['orders'] > 255
                ) {
                    return ResponseHelper::error($response, '参数ORDERS错误');
                }
                $updateData = ['orders' => $params['orders']];
                $updateRs = SystemMenu::where('id', $params['id'])
                    ->update($updateData);
                if ($updateRs != 1) {
                    return ResponseHelper::error($response, '更新错误');
                }

                SystemMenu::clearAllMenuCache();

                return ResponseHelper::success($response);
            } elseif (isset($params['action']) && $params['action'] == 'status') {
                if (!isset($params['status']) || !in_array($params['status'], ['true', 'false'])) {
                    return ResponseHelper::error($response, '参数ORDERS错误');
                }

                $updateData = ['status' => $params['status'] == 'true' ? 1 : 2];
                $updateRs = SystemMenu::where('id', $params['id'])
                    ->update($updateData);
                if ($updateRs != 1) {
                    return ResponseHelper::error($response, '更新错误');
                }

                SystemMenu::clearAllMenuCache();

                return ResponseHelper::success($response);
            } else {
                return ResponseHelper::error($response, '参数ACTION错误');
            }
        }
    }
}
